
package com.plz.afmt.common;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.hutool.core.util.StrUtil;
import com.google.gson.Gson;
import com.plz.afmt.entity.UserEntity;
import com.plz.afmt.enums.CacheKeyEnum;
import com.plz.afmt.service.ChatService;
import com.plz.afmt.service.SysParamsService;
import com.plz.afmt.service.UserService;
import com.plz.afmt.transfer.UserTransfer;
import com.plz.afmt.vo.UserVo;
import com.plz.common.exception.BusinessException;
import com.plz.framework.cache.CacheService;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.plz.afmt.dto.WeChatLoginDTO;
//import com.plz.afmt.websocket.WebSocketServer;

import java.io.IOException;
import java.time.LocalDateTime;

@Component
@Slf4j
public class CommonService {

    @Autowired
    private CacheService redisService;
    @Autowired
    private UserService userService;
    @Autowired
    private SysParamsService sysParamsService;
    @Autowired
    private UserTransfer userTransfer;
    @Autowired
    private ChatService chatService;

    public void init() {
        Object o = redisService.get(CacheKeyEnum.GPT_KEY.getCode());
        if (o == null) {
            throw new BusinessException("暂未配置apikey");
        }

        String pro = "127.0.0.1";//本机地址
        int pro1 = 7890; //代理端口号
    }
//    public void onMessage( String msg, WebSocketServer webSocketServer) throws IOException {
//        UserEntity user = userService.getById(webSocketServer.userId);
//        if(user.getSessionId()==null){
//            chatService.createChat();
//        }
//        String answer = chatService.question(msg, user);
//        webSocketServer.session.getBasicRemote().sendText(answer);
//        webSocketServer.session.getBasicRemote().sendText("[DONE]");
//        //存提问记录和回答
//        log.info("问题是:"+msg);
//        log.info("回答是:"+answer);
//     }
    public UserVo miniAppLogin(WeChatLoginDTO dto) {
        String code = dto.getCode();
        String encryptedData = dto.getEncryptedData();
        String iv = dto.getIv();
        String miniAppAppid = sysParamsService.getValue("mini_app_appid");
        String miniAppSecret = sysParamsService.getValue("mini_app_secret");
        if (StrUtil.isBlank(miniAppAppid) || StrUtil.isBlank(miniAppSecret)) {
            throw new BusinessException("请先配置小程序");
        }
        try {
            WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
            config.setMsgDataFormat("JSON");
            config.setAppid(miniAppAppid);
            config.setSecret(miniAppSecret);
            WxMaService wxMaService = new WxMaServiceImpl();
            wxMaService.setWxMaConfig(config);
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            String openid = session.getOpenid();
            String unionId = openid;//就当小程序公众号等没有在微信开放平台绑定在一起的情况
            //如果开启了UnionId
            if (StrUtil.isNotBlank(session.getUnionid())) {//取到了 说明绑定了
                unionId = session.getUnionid();
            }
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService()
                    .getPhoneNoInfo(session.getSessionKey(), encryptedData, iv);
            String phoneNumber = phoneNoInfo.getPhoneNumber();//用户手机号
            UserEntity user = null;
            if (StrUtil.isNotBlank(phoneNumber)) {//取到手机号了
                user = userService.getByMobile(phoneNumber);
                if (user == null) {//根据手机号没查到
                    //那根据UnionId 查询
                    user = userService.getUserByUnionId(unionId);
                    //查到了就绑定手机号 没查到就是新用户
                    if (user == null) {

                        user = new UserEntity("微信用户", openid, null);
                        user.setWxUnionid(unionId);
                        user.setUsername(phoneNumber);
                        user.setMobile(phoneNumber);

                        userService.save(user);
                    }
                } else {
                    //这里是查到了 不管别的  给这狗日的把openid和unionId绑定起
                    user.setWxUnionid(unionId);
                    user.setWxOpenid(openid);
                    userService.updateById(user);
                }
            } else {//没取到手机号
                //先根据unionId查询是否由用户
                user = userService.getUserByUnionId(unionId);
                if (user == null) {//没查到就是新用户 查到了直接登录

                    user = new UserEntity("微信用户", openid, null);
                    user.setWxUnionid(unionId);

                    userService.save(user);
                }
            }
            //生成token
            String creatToken = userService.creatToken(user);

            UserVo userVo = userTransfer.po2vo(user);
            userVo.setToken(creatToken);
            return userVo;
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return null;
    }
}
